package it.salvatore.parser;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class LoginTask implements Runnable{

	private String mUser;
	private String mPassword;
	private RemoteServiceClientListener mCallBack;



	public LoginTask(String mUser, String mPassword,
			RemoteServiceClientListener mCallBack) {
		super();
		this.mUser = mUser;
		this.mPassword = mPassword;
		this.mCallBack = mCallBack;
	}



	@Override
	public void run() {
		// prima chiamata per ottenere il jsessionid
		//TODO Spostare URL nelle risorse
		Response res;
		boolean successful=false;
		int reason;
		String jsessionid = null;
		try {
			res = Jsoup.connect("http://opac.provincia.bergamo.it/public/opac/documentSearchFormFullText.seam")
					.method(Method.GET)
					.execute();

			Document doc = res.parse();	 

			Element logiForm=doc.getElementById("loginForm");
			String actionToCall= logiForm.attr("action");
			
			//seconda chiamata per eseguire la login
			Response res2;

			res2 = Jsoup.connect("http://opac.provincia.bergamo.it"+actionToCall)
					.data("loginForm","loginForm","loginForm:usernameIn", mUser,"loginForm:passwordIn", mPassword,"loginForm:login","Accedi","javax.faces.ViewState","j_id1").method(Method.POST)
					.execute();
			Document doc2 = res2.parse();	
			Element logged=doc2.getElementById("loggedForm");
			
			jsessionid = actionToCall.substring(actionToCall.indexOf("=")+1,actionToCall.length());
			
			if (logged!=null){
				//login eseguita con successo;
				successful=true;
			}
			else {
				//TODO gesire errori di login: ex password errata
			}
			
		} catch (IOException e) {
			mCallBack.loginFailed(e);
			
		}
		 
		if (successful){
			mCallBack.loginPerformed(jsessionid);
		}
		else
		{
			mCallBack.loginFailed(404);
		}



	}

}
